//
//  ShoperViewController.m
//  EasyToTesco
//
//  Created by mc on 16/1/31.
//  Copyright © 2016年 Jack. All rights reserved.
//  商家首页,,,要获取当前定位的城市的...

#import "ShoperViewController.h"

#import "HeaderFileForEasyToTesco.h"
#import "HomeTableViewCell.h"
//刷新控件头文件
#import "SDRefresh.h"
//下拉列表
#import "DropDownListView.h"

#import "ShoperDetailViewController.h"

//
#import "CWStarRateView.h"
#import "AFNetworking.h"
#import "UIImageView+WebCache.h"

#import "GPDateView.h"
#import "SVProgressHUD.h"


#import "ShopsDetailViewController.h"
//get location


@interface ShoperViewController ()<UITableViewDataSource, UITableViewDelegate>
{
    NSMutableArray *chooseArray;
    
    
    
}

@property (nonatomic, strong)NSMutableArray *shoperarray;

@property(nonatomic, strong)UITableView *shoperTableview;
//刷新控件
@property (nonatomic, weak) SDRefreshFooterView *refreshFooter;
@property (nonatomic, weak) SDRefreshHeaderView *refreshHeader;

@property (nonatomic,copy)NSString *provinceLabel;
@property (nonatomic,copy)NSString *cityLabel;
@property (nonatomic,copy)NSString *areaLabel;

//刷新页码
@property(nonatomic)NSInteger refreshIndex;

@end

@implementation ShoperViewController

- (void)loadView {
    [super loadView];
    [SVProgressHUD show];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [SVProgressHUD dismiss];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //
    self.refreshIndex = 1;
    
    // Do any additional setup after loading the view from its nib.
    chooseArray = [NSMutableArray arrayWithArray:@[
                                                   @[@"全部",@"0-1",@"0-2",@"0-3"],
                                                   @[@"全程",@"1-0",@"1-1"], @[@"排序", @"2-0", @"2-1"], @[@"筛选", @"3-0", @"3-1"]
                                                   ]];
    [self addShoperViewUI];
}

- (void)addShoperViewUI {
    self.shoperarray = [@[]mutableCopy];
    
    self.titleLabel.text = @"商家";
    
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(WEITH - 50, 5, 40, 40)];
    
    [btn setTitle:@"筛选" forState:UIControlStateNormal];
    
    btn.titleLabel.font = [UIFont systemFontOfSize:15];
    
//    btn.backgroundColor = [UIColor redColor];
    
    [btn setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    
    [btn addTarget:self action:@selector(clickScreenBtn) forControlEvents:UIControlEventTouchUpInside];
    
    [self.secondView addSubview:btn];
    
//    [self addShoperSelectBtn];
    
    [self addShoperTableview];
    [self setupshoperHeader];
    [self setupshoperFooter];
    
    [self ShopDatasources];
}

- (void)clickScreenBtn {
    
    GPDateView * dateView = [[GPDateView alloc] initWithFrame:CGRectMake(0, HIGHT-250, WEITH, 250) Data:nil];
    
    [dateView showPickerView];
    
    dateView.ActionDistrictViewSelectBlock = ^(NSString *desStr,NSDictionary *selectDistrictDict){

#warning 数据未请求！！！
        
//        self.provinceLabel = [selectDistrictDict objectForKey:Key_DistrictSelectProvince];
//        self.cityLabel = [selectDistrictDict objectForKey:Key_DistrictSelectCity];
//        self.areaLabel = [selectDistrictDict objectForKey:Key_DistrictSelectProvinceSub];
        
//        self.provinceLabel = [selectDistrictDict objectForKey:@"DistrictSelectProvince"];
        self.cityLabel = [selectDistrictDict objectForKey:@"DistrictSelectCity"];
        self.areaLabel = [selectDistrictDict objectForKey:@"DistrictSelectProvinceSub"];

//        self.provinceLabel = @"微商";
//        self.cityLabel = @"南昌";
//        self.areaLabel = @"东湖区";
        self.cityLabel = [self.cityLabel substringWithRange:NSMakeRange(0, 2)];
        
        AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
        mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
        
        NSDictionary *param = @{@"city":self.cityLabel, @"county":self.areaLabel, @"type_name":@"", @"P":@1};
        
        [mgr POST:@"http://www.ylgw8.com/AppShop/Getshops" parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
            //        NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            
            
            NSDictionary *dic = [self toArrayOrNSDictionary:responseObject];
            
            self.shoperarray = [NSMutableArray arrayWithArray:dic[@"data"]];
            
            
            NSLog(@"%@", self.shoperarray);
            
            [self.shoperTableview reloadData];
        } failure:^(AFHTTPRequestOperation *operation,NSError *error)
         {
             //         operation.response.statusCode;//404 401之类
             //         NSLog(@"数据请求错误原因:%@", error);
             //         NSLog(@"数据请求错误码:%ld", (long)operation.response.statusCode);
         }];
//
    };
}

- (void)addShoperSelectBtn {
    
//    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.firstView.frame), WEITH, 40)];
//    view.backgroundColor = [UIColor yellowColor];
    DropDownListView * dropDownView = [[DropDownListView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.firstView.frame), WEITH, 40) dataSource:self delegate:self];
    dropDownView.mSuperView = self.view;
    
    [self.view addSubview:dropDownView];
    
}

- (void)addShoperTableview {
    self.shoperTableview = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(self.firstView.frame), WEITH, HIGHT-CGRectGetHeight(self.firstView.frame)-self.tabBarController.tabBar.frame.size.height) style:UITableViewStylePlain];
    self.shoperTableview.dataSource = self;
    self.shoperTableview.delegate = self;
    self.shoperTableview.rowHeight =90;
    [self.view addSubview:self.shoperTableview];
}


#pragma mark -- UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.shoperarray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"HomeTableViewCell";
    HomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"HomeTableViewCell" owner:nil options:nil] lastObject];
         cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [self setLeftViewWithTextField:cell.location imageName:@"Icon_-Location-pin.png"];
        [self setLeftViewWithTextField:cell.NumOfBuy imageName:@"men-gray-icon.png"];
    }
    NSString *string = [NSString stringWithFormat:@"http://www.ylgw8.com/Uploads/sjpic/m_%@", [self.shoperarray[indexPath.row] objectForKey:@"sdpic"]];
    [cell.picImage sd_setImageWithURL:[NSURL URLWithString:string] placeholderImage:[UIImage imageNamed:@"cellpic.png"]];
    
    cell.shopTitle.text = [NSString stringWithFormat:@"%@", [self.shoperarray[indexPath.row] objectForKey:@"title"]];
    cell.location.text = [NSString stringWithFormat:@"%@", [self.shoperarray[indexPath.row] objectForKey:@"county"]];
    cell.shopStar.scorePercent = [[NSString stringWithFormat:@"%@", [self.shoperarray[indexPath.row] objectForKey:@"score"]] floatValue];
    //评分
    cell.personPrice.text = [NSString stringWithFormat:@"%@", [self.shoperarray[indexPath.row] objectForKey:@"score"]];
    //范围
    cell.NumOfPerson.text = [NSString stringWithFormat:@"%@", [self.shoperarray[indexPath.row] objectForKey:@"zycp"]];
    //评价人数
    cell.NumOfBuy.text = [NSString stringWithFormat:@"%@人评价", [self.shoperarray[indexPath.row] objectForKey:@"m"]];
    
    
    return cell;
}


#pragma mark -- UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"%ld--%ld", indexPath.section, indexPath.row);
    
    ShopsDetailViewController *shopdetailVC = [[ShopsDetailViewController alloc] init];
    shopdetailVC.shopsID = [NSString stringWithFormat:@"%@", [self.shoperarray[indexPath.row] objectForKey:@"id"]];
    [self presentViewController:shopdetailVC animated:YES completion:nil];
    
}

/**
 *  给UITextField设置右侧的图片
 *
 *  @param textField UITextField
 *  @param imageName 图片名称
 */

-(void)setLeftViewWithTextField:(UITextField *)textField imageName:(NSString *)imageName{
    
    UIImageView *rightView = [[UIImageView alloc]init];
    
    rightView.image = [UIImage imageNamed:imageName];
    rightView.frame = CGRectMake(0, 0, CGRectGetHeight(textField.frame), CGRectGetHeight(textField.frame));
    rightView.contentMode = UIViewContentModeCenter;
    textField.leftView = rightView;
    textField.leftViewMode = UITextFieldViewModeAlways;
}



- (void)setupshoperHeader{
    //添加下拉刷新对象
    SDRefreshHeaderView *refreshHeader = [SDRefreshHeaderView refreshView];
    
    //     默认是在navigationController环境下，如果不是在此环境下，请设置
    refreshHeader.isEffectedByNavigationController = NO;
    
    //加入到目标tableview上
    [refreshHeader addToScrollView:self.shoperTableview];
    
    //添加下拉加载内容的方法
    __weak SDRefreshHeaderView *weakRefreshHeader = refreshHeader;
    __weak typeof(self) weakSelf = self;
    refreshHeader.beginRefreshingOperation = ^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
#pragma mark -- 加载数据的方法
            
            [weakSelf ShopDatasources];
            
            [weakSelf.shoperTableview reloadData];
            [weakRefreshHeader endRefreshing];
        });
    };
    
    // 进入页面自动加载一次数据
    [refreshHeader autoRefreshWhenViewDidAppear];
}

- (void)setupshoperFooter{
    SDRefreshFooterView *refreshFooter = [SDRefreshFooterView refreshView];
    refreshFooter.isEffectedByNavigationController = NO;
    [refreshFooter addToScrollView:self.shoperTableview];
    [refreshFooter addTarget:self refreshAction:@selector(footerRefresh)];
    _refreshFooter = refreshFooter;
}


- (void)footerRefresh{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
#pragma mark -- 加载数据的方法
        [self loadMoreDatas];
        
        [self.shoperTableview reloadData];
        [self.refreshFooter endRefreshing];
    });
}


#pragma mark -- dropDownListDelegate
-(void) chooseAtSection:(NSInteger)section index:(NSInteger)index
{
    NSLog(@"童大爷选了section:%ld ,index:%ld, %@",section, index, chooseArray[section][index]);
    
    
#pragma mark -- 选择后刷新页面
    [self.shoperTableview reloadData];
    
}

#pragma mark -- dropdownList DataSource
-(NSInteger)numberOfSections
{
    return [chooseArray count];
}
-(NSInteger)numberOfRowsInSection:(NSInteger)section
{
    NSArray *arry =chooseArray[section];
    return [arry count];
}
-(NSString *)titleInSection:(NSInteger)section index:(NSInteger) index
{
    return chooseArray[section][index];
}
-(NSInteger)defaultShowSection:(NSInteger)section
{
    return 0;
}

//下拉刷新数据
- (void)loadMoreDatas
{
//    [self.shoperarray removeAllObjects];

    self.refreshIndex ++;
    
    [self ShopDatasources];
}

- (void)ShopDatasources {
        AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSString *city = @"丽水";
    NSString *county = @"";
    NSString *type_name = @"";
    NSString *P = [NSString stringWithFormat:@"%ld",self.refreshIndex];
    

    NSDictionary *param = @{@"city":[NSString stringWithFormat:@"%@", city], @"county":[NSString stringWithFormat:@"%@", county], @"type_name":[NSString stringWithFormat:@"%@", type_name], @"p":[NSString stringWithFormat:@"%@", P]};
    
    [mgr POST:@"http://www.ylgw8.com/AppShop/Getshops" parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        
        
        NSDictionary *dic = [self toArrayOrNSDictionary:responseObject];
        
        NSArray *array = [NSMutableArray arrayWithArray:dic[@"data"]];
        
        [self.shoperarray addObjectsFromArray:array];
        
        
        NSLog(@"%@", self.shoperarray);
        NSLog(@"%ld",self.shoperarray.count);
        
        [self.shoperTableview reloadData];
    } failure:^(AFHTTPRequestOperation *operation,NSError *error)
     {
         //         operation.response.statusCode;//404 401之类
//         NSLog(@"数据请求错误原因:%@", error);
//         NSLog(@"数据请求错误码:%ld", (long)operation.response.statusCode);
     }];
}


// 将JSON串转化为字典或者数组
- (id)toArrayOrNSDictionary:(NSData *)jsonData{
    NSError *error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                    options:NSJSONReadingAllowFragments
                                                      error:&error];
    
    if (jsonObject != nil && error == nil){
        return jsonObject;
    }else{
        // 解析错误
        return nil;
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
